package com.xunsiya.common.config.util;

import com.jcraft.jsch.*;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.Map;
import java.util.Properties;

/**
 * ftp连接
 * @author panjun
 * @version 1.0
 * <p>
 * <p>修订人		修订时间			描述信息
 * <p>-----------------------------------------------------
 * <p>panjun	2018-11-5		初始创建
 */
public class SftpChannel {

    /** AWS 需要的可以
    public final String priKeyFile = "/usr/local/topvisionupload/shanghai-aws.pem"; */
    public final String priKeyFile = "";
    public final String passphrase = "";

    Session session = null;
    Channel channel = null;

    private static final Logger LOG = Logger.getLogger(SftpChannel.class);

    public ChannelSftp getChannel(Map<String, String> sftpDetails, int timeout) throws JSchException {

        String ftpHost = sftpDetails.get(SftpConstants.SFTP_REQ_HOST);
        String port = sftpDetails.get(SftpConstants.SFTP_REQ_PORT);
        String ftpUserName = sftpDetails.get(SftpConstants.SFTP_REQ_USERNAME);
        String ftpPassword = sftpDetails.get(SftpConstants.SFTP_REQ_PASSWORD);

        int ftpPort = SftpConstants.SFTP_DEFAULT_PORT;
        if (!StringUtils.isEmpty(port)) {
            ftpPort = Integer.valueOf(port);
        }

        // 创建JSch对象
        JSch jsch = new JSch();
        // 秘钥登录
        if (!StringUtils.isEmpty(priKeyFile)) {
            if (!StringUtils.isEmpty(passphrase)) {
                jsch.addIdentity(priKeyFile, passphrase);
            } else {
                jsch.addIdentity(priKeyFile);
            }
        }
        // 根据用户名，主机ip，端口获取一个Session对象
        session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
        LOG.info("Session created.");
        // 设置密码
        if (ftpPassword != null) {
            session.setPassword(ftpPassword);
        }
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        // 为Session对象设置properties
        session.setConfig(config);
        // 设置timeout时间
        session.setTimeout(timeout);
        // 通过Session建立链接
        session.connect();
        LOG.info("Session connected.");

        LOG.info("Opening Channel.");
        // 打开SFTP通道
        channel = session.openChannel("sftp");
        // 建立SFTP通道的连接
        channel.connect();
        LOG.info("Connected successfully to ftpHost = " + ftpHost + ",as ftpUserName = " + ftpUserName
                + ", returning: " + channel);
        return (ChannelSftp) channel;
    }

    public void closeChannel() throws Exception {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }
}